package tool;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.StringUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ddRobot {

    //?????????10s
    public static final int TIME_OUT = 10000;

    /**
     * ????????????????https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq
     *
     * @param webhook
     * @param secret     ??????? 3?1????????????????? ?? ???????????? ?????????????????? secret??SE??????????????IP??????????
     * @param content    ????????
     * @param mobileList ??????????????????? ???????
     * @return
     */
    public static String sendMsg(String webhook, String secret, String content, List<String> mobileList) {
        try {
            //????????????????????????webhook??
            if (!StringUtils.isEmpty(secret)) {
                Long timestamp = System.currentTimeMillis();
                String sign = getSign(timestamp, secret);
                webhook = new StringBuilder(webhook)
                        .append("&timestamp=")
                        .append(timestamp)
                        .append("&sign=")
                        .append(sign)
                        .toString();
            }
//            System.out.println("webhook:" + webhook);

            //???????????
            boolean isAtAll = false;
            //???????????
            String reqStr = buildReqStr(content, isAtAll, mobileList);
            //?????????http????
            String result = postJson(webhook, reqStr);
//            log.info("??????result == " + result);
            return result;
        } catch (Exception e) {
//            log.info("????????? ?????{}", e.getStackTrace());
            return null;
        }
    }

    /**
     * ?????????
     * ??????????? text
     *
     * @param content
     * @return
     */
    private static String buildReqStr(String content, boolean isAtAll, List<String> mobileList) {
        //???????
        Map<String, String> contentMap = new HashMap<>();
        contentMap.put("content", content);
        //????
        Map<String, Object> atMap = new HashMap<>();
        //1.???????????
        atMap.put("isAtAll", isAtAll);
        //2.???????????????????
        atMap.put("atMobiles", mobileList);
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("msgtype", "text");
        reqMap.put("text", contentMap);
        reqMap.put("at", atMap);
        return JSON.toJSONString(reqMap);
    }


    private static String postJson(String url, String reqStr) {
        String body = null;
        try {
            body = HttpRequest.post(url).body(reqStr).timeout(TIME_OUT).execute().body();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return body;
    }

    /**
     * ???????????????
     * ???????????????????secret??SE???
     *
     * @param timestamp
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     * @throws InvalidKeyException
     */
    private static String getSign(Long timestamp, String secret) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
//        System.out.println("singn:" + sign);
        return sign;
    }

    public static void main(String[] args) {
        String secret = "";
        String webhook="";

        List<String> mobileList = Lists.newArrayList();
        mobileList.add("18760370618");
        String content=HttpRequest.get("http://www.weather.com.cn/data/cityinfo/101230201.html").timeout(TIME_OUT).execute().body();

        System.out.println(sendMsg(webhook, secret, content, mobileList));
    }

}
